package com.webcat.controller;

import com.webcat.entity.AiResponse;
import com.webcat.entity.Response;
import com.webcat.entity.SseResponse;
import com.webcat.service.ChatService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import java.util.List;

@RestController
@RequestMapping("/ai")
@Slf4j
public class AiChatController {

    @Resource
    private ChatService chatService;

    @GetMapping(value = "/start")
    public AiResponse<String> start() {
        return AiResponse.success(chatService.start());
    }

    @GetMapping(value = "/streamChat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<SseResponse<Object>> streamChat(@RequestParam("chatId") String chatId, String message, String datasetId, String businessId) {
        return chatService.streamChat(chatId, message, datasetId, businessId, false);
    }

    @GetMapping(value = "/chat")
    public AiResponse<String> chat(@RequestParam("chatId") String chatId, @RequestParam("message") String message, String businessId) {
        return AiResponse.success(chatId, chatService.chat(chatId, message, businessId, false));
    }

    @GetMapping(value = "/getTools")
    public Response<List<ToolCallback>> getTools() {
        return Response.success(chatService.getTools());
    }

    @PostMapping(value = "/streamChatWithFile", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChatWithFile(@RequestParam("chatId") String chatId, String message, @RequestParam("file") MultipartFile file) {
        return chatService.streamChatWithFile(chatId, message, file, false).map(res -> res.getData() == null?"":res.getData().toString());
    }
}
